package com.example.demoofimagedownloadapp.presenter;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.RemoteException;
import android.util.Log;

import com.example.demoofimagedownloadapp.bean.MessageEvent;
import com.example.demoofimagedownloadapp.contract.MainContract;
import com.example.demoofimagedownloadapp.model.DownloadModel;
import com.example.demoofimagedownloadapp.model.IDownloadModel;
import com.example.demoofimagedownloadapp.utils.Constants;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


/**
 * @author ts
 */
public class MainPresenter extends BasePresenter<MainContract.View> implements MainContract.Presenter {
    private static final String TAG = MainPresenter.class.getName();
    MainContract.View mView = null;
    IDownloadModel mModel;
    Context mContext;

    public MainPresenter (Context context) {
        this.mContext = context;
        mModel = new DownloadModel(context);
    }

    @Override
    public void setView(MainContract.View view) {
        this.mView = view;
    }

    @Override
    public void start() {
        super.start();
        mModel.addListener();
        EventBus.getDefault().register(this);

    }



    @Override
    public void stop() {
        super.stop();
        mModel = null;
        EventBus.getDefault().unregister(this);
    }

    @Override
    public boolean startDownload() throws RemoteException {
        boolean flag = mModel.startDownload();
        Log.d(TAG, "startDownload: " + flag);
        if(flag == true){
            return true;
        }
        return false;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MessageEvent messageEvent) throws RemoteException {
        switch (messageEvent.getMessage()){
            case Constants.DOWNLOAD_FLAG_DONE:
                Bitmap bitmap = messageEvent.getBitmap();
                // TODO: listen
                if (bitmap == null){
                    Log.d(TAG, "onMoonEvent: getBitmap NULL ERROR");
                    return;
                }
                Log.d(TAG, "onMoonEvent: DONE");
                mView.updateImage(bitmap);
                break;
            case Constants.DOWNLOAD_FLAG_PROGRESS:
                // TODO: listen
                Log.d(TAG, "onMoonEvent: "+messageEvent.getProgress());
                mView.updateProgress(messageEvent.getProgress());
                break;
            default:
                break;
        }
    }

    @Override
    public boolean cancelDownload() throws RemoteException {
        boolean flag = mModel.cancelDownload();
        Log.d(TAG, "cancelDownload: " + flag);
        if(flag){
            return true;
        }
        return false;
    }
}
